package org.caowei.samples.sevice;

import java.util.ArrayList;
import java.util.List;

import org.caowei.samples.dao.ISubjectDAO;
import org.caowei.samples.dao.IUserDAO;
import org.caowei.samples.model.Subject;
import org.caowei.samples.model.User;
import org.caowei.samples.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SubjectServiceImpl implements ISubjectService{
	
	@Autowired
	private ISubjectDAO subjectDAO;
	
	@Autowired
	private IUserDAO iUserDAO;
	
	@Override
	public List<String> getAllUserBySubject(Integer subjectId) {
		return subjectDAO.getAllUserBySubject(subjectId);
	}
	
	//(non-Javadoc) 获取所有学生的Service代码
	@Override
	public List<UserVO> getAllStudent(){
		List<User> userList = iUserDAO.getAllStudent();
		List<UserVO> resultList = new ArrayList<UserVO>();
		for(User user : userList){
			UserVO vo = new UserVO();
			BeanUtils.copyProperties(user, vo);
			resultList.add(vo);
		}
		return resultList;
	}
	
	@Override
	public List<Subject> findAllSubjects() throws Exception {
		return subjectDAO.findAllSubjects();
	}

	@Override
	public void createSubject(Subject subject) throws Exception {
		subjectDAO.createSubject(subject);
	}

	@Override
	public void editSubject(Subject subject) throws Exception {
		subjectDAO.editSubject(subject);
	}

	@Override
	public Subject getSubjectById(int id) throws Exception {
		return subjectDAO.getSubjectById(id);
	}

	@Override
	public void deleteSubject(int id) throws Exception {
		subjectDAO.deleteSubject(id);
	}

	//保存修改
	@Override
	public void saveSubjectStudent(List<String> subjectStudents, Integer subjectId) throws RuntimeException {
		List<String> dbSubjectUserList = subjectDAO.getAllUserBySubject(subjectId);//获取当前科目关联的所有学生
		
		List<String> insertList = new ArrayList<String>();
		List<String> delList = new ArrayList<String>();
		
		//1有，2无的情况
		//判断哪些学生是新勾选上的
		for(String selectedUser : subjectStudents){
			if(!dbSubjectUserList.contains(selectedUser)){
				insertList.add(selectedUser);
			}
		}
		
		//1有，2无的情况
		//判断哪些学生本是勾选上的，现在去掉勾选的
		for(String selectedUser : dbSubjectUserList){
			if(!subjectStudents.contains(selectedUser)){
				delList.add(selectedUser);
			}
		}
		//insertList 分别保存
		subjectDAO.insertSubjectUsers(insertList,subjectId);
		//delList 分别删除
		subjectDAO.deleteSubjectUsers(delList,subjectId);
	}

	@Override
	public void TchangeStatus(Integer subjectId) throws Exception {
		Subject SubStatus = subjectDAO.getSubjectById(subjectId);
		if(SubStatus.getStatus() == 0){
			SubStatus.setStatus(1);
			subjectDAO.editSubject(SubStatus);
		}else{
			SubStatus.setStatus(0);
			subjectDAO.editSubject(SubStatus);
		}
		
	}

}
